import type { ImUser } from '@/api/types/userWrapper'
import { defineStore } from 'pinia'

export const useImTokenStore = defineStore(
  'imToken',
  () => {
    const accessToken = ref('')
    const accessExpire = ref(0)

    const refreshToken = ref('')
    const refreshExpire = ref(0)

    const setImToken = (res: ImUser) => {
      accessToken.value = res.accessToken || ''
      accessExpire.value = Date.now() + (res.accessTokenExpiresIn || 0) * 1000

      refreshToken.value = res.refreshToken || ''
      refreshExpire.value = Date.now() + (res.refreshTokenExpiresIn || 0) * 1000

      uni.setStorageSync('im_access_token', accessToken.value)
      uni.setStorageSync('im_access_expire', accessExpire.value)

      uni.setStorageSync('im_refresh_token', refreshToken.value)
      uni.setStorageSync('im_refresh_expire', refreshExpire.value)
    }

    const loadFromStorage = () => {
      accessToken.value = uni.getStorageSync('im_access_token') || ''
      accessExpire.value = uni.getStorageSync('im_access_expire') || 0

      refreshToken.value = uni.getStorageSync('im_refresh_token') || ''
      refreshExpire.value = uni.getStorageSync('im_refresh_expire') || 0
    }
    loadFromStorage()

    const isAccessExpired = computed(() => Date.now() >= accessExpire.value)
    const isRefreshExpired = computed(() => Date.now() >= refreshExpire.value)

    const getValidImToken = () => {
      return isAccessExpired.value ? '' : accessToken.value
    }
    /** 清理 IM token */
    const logout = () => {
      accessToken.value = ''
      accessExpire.value = 0
      refreshToken.value = ''
      refreshExpire.value = 0
      uni.removeStorageSync('im_access_token')
      uni.removeStorageSync('im_access_expire')
      uni.removeStorageSync('im_refresh_token')
      uni.removeStorageSync('im_refresh_expire')
    }
    return {
      accessToken,
      refreshToken,

      isAccessExpired,
      isRefreshExpired,
      getValidImToken,

      setImToken,
      logout,
    }
  },
  { persist: true },
)
